package com.bdf.ipharma.communication;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import ar.com.bdf.ipharma.communications.serial.BasicWritePort;
import ar.com.bdf.ipharma.protocolo.model.HandShake;
import ar.com.bdf.ipharma.protocolo.model.ParserTrama;

import com.bdf.ipharma.config.Session;
import com.bdf.ipharma.operation.Operation;
import com.bdf.ipharma.operation.OperationAbrirPuerta;
import com.bdf.ipharma.operation.OperationCerrarPuerta;
import com.bdf.ipharma.operation.OperationExtraer;
import com.bdf.ipharma.starter.McdMain;
import com.bdf.ipharma.starter.McdPrs;

public class Task {

	private String port;
	private Long timeInterOperation;
	private List<Operation> operations = new ArrayList<Operation>();
	private Integer identificador = 1;
	private McdMain mcdMain;
	private List<HandShake> handShakeList;
	
	static final Logger logger = Logger.getLogger(Task.class);
	
	public Task(McdMain mcdMain) {
		super();
		this.handShakeList = new ArrayList<HandShake>();
		this.mcdMain = mcdMain;
	}

	public Integer getIdentificador() {
		return identificador;
	}

	public void setIdentificador(Integer identificador) {
		this.identificador = identificador;
	}

	public List<Operation> getOperations() {
		return operations;
	}

	public void setOperations(List<Operation> operations) {
		this.operations = operations;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public Long getTimeInterOperation() {
		return timeInterOperation;
	}

	public void setTimeInterOperation(Long timeInterOperation) {
		this.timeInterOperation = timeInterOperation;
	}



	private Long getTimeInterOperation(Operation operation){
		Integer timeInterOperation = 1;
		Integer tiempoTotal = 0;
		if(operation instanceof OperationExtraer){
			OperationExtraer operacionExtrae = (OperationExtraer)operation;
			operacionExtrae.getCantVueltas();
			tiempoTotal = operacionExtrae.getCantVueltas() * timeInterOperation;
		}
		
		return Long.decode(String.valueOf(tiempoTotal));
	}
	
	public void execute() {
		for (Operation operation : operations) {
			operation.setIdentificador(identificador);
			for (int i = 1; i <= operation.getCountOperation(); i++) {
				HandShake handshake = operation.getHandShake();
				if (handshake != null){
					if(operation instanceof OperationExtraer){
						logger.debug("Preparando para realizar operacion extraer");
					}
					if(operation instanceof OperationAbrirPuerta){
						logger.debug("Preparando para realizar operacion Abrir puerta");
					}
					if(operation instanceof OperationCerrarPuerta){
						logger.debug("Preparando para realizar operacion Cerrar puerta");
					}
					logger.debug("Preparando Hanshake a enviar");
					
					String serializable = getParser().serializable(handshake.getRequest());
					sendByCom(serializable);
					
//					while(true){ 
//		            	if (this.mcdMain.getIsResponseSuccessFull()!=null) {
//		                     Thread.yield();
//		                    break;
//		            	}
//	            	}
					// Seteo un slp para que la bandeja vaya a buscar el producto...
					Thread slp = new Thread();
					try {
						//slp.sleep(5000);
						slp.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					this.timeInterOperation = getTimeInterOperation(operation);
					dormir();
				}
			}
		}

	}

	private ParserTrama getParser() {
		return new ParserTrama();
	}

	private void dormir() {
		try {
			logger.info("sleeping... TimeInterOperation --> " + this.timeInterOperation * 5000L);
			Thread.sleep(this.timeInterOperation * 3000L);
			
		} catch (Exception e) {			
			logger.error("No se pudo dormir " + timeInterOperation + " segundos" +e.getMessage());
		}
	}

	private boolean sendByCom(String serializable) {
		boolean isSuccesfull = false;
		try {
			logger.info(port + "===> " + serializable);
			BasicWritePort handler = new BasicWritePort(port);
			logger.debug("String serialiado :" + serializable);
			logger.debug("Se escribira en el puerto....");
			handler.write(serializable);
			logger.debug("Se cerrara la conexion");
			handler.close();
			logger.debug("conexion cerrada");
			isSuccesfull=true;
			return isSuccesfull;
		} catch (Exception e) {
			logger.debug("EXCEPCION SENDBYCOM :" + e.getMessage());
			return isSuccesfull;
		}
	}
	
	public boolean isOperationsSuccesfull(){
		return this.mcdMain.getIsResponseSuccessFull().booleanValue();
	}
}
